﻿using DynamicAuthorization.Sdk.Abstarctions;
using DynamicAuthorization.Sdk.Attributes;
using DynamicAuthorization.Sdk.Impl;
using DynamicAuthorization.Sdk.Serialization;
using Microsoft.AspNetCore.Authorization;
using System.Reflection;
using System.Security.Claims;

namespace OA.Infrastructure.Controllers;

[Route("api/[controller]")]
[ApiController]
[Authorize(Policy = "ams")]
[PermisstionDefinition("权限管理")]
public class PermissionController : ControllerBase
{
    private readonly IUserService _userService;
    private readonly IGrantService _grantService;

    public PermissionController(IUserService userService, IGrantService grantService)
    {
        _userService = userService;
        _grantService = grantService;
    }

    [HttpGet]
    [PermisstionDefinition("获取全部权限")]
    public IActionResult GetAllPermissions()
    {
        var metadata = new GrantTypeMetadata(Assembly.GetExecutingAssembly());

        var seria = metadata.ToSerialization();

        return Ok(seria);
    }

    [HttpGet("self")]
    [PermisstionDefinition("获取个人权限")]
    public async Task<IActionResult> GetSelfPermissionsAsync()
    {
        var claim = HttpContext.User.Claims.FirstOrDefault(n => n.Type is "name" or ClaimTypes.Name);

        if (claim is null)
        {
            return Unauthorized();
        }

        var routers = await _userService.GetUserRoutesAsync(claim.Value, HttpContext.RequestAborted);

        var grants = await _userService.GetUserGrantsAsync(claim.Value, HttpContext.RequestAborted);

        var roles = await _userService.GetRolesNameAsync(claim.Value, HttpContext.RequestAborted);

        var seria = _grantService.Analyze(grants!).ToSerialization().WithRouters(routers);

        return Ok(new
        {
            seria.Functions,
            seria.Modules,
            seria.RejectModules,
            seria.Routers,
            roles
        });
    }

    [HttpGet("route")]
    [PermisstionDefinition("获取路由权限")]
    public async Task<IActionResult> GetViewRoutesAsync()
    {
        var claim = HttpContext.User.Claims.FirstOrDefault(n => n.Type is "name" or ClaimTypes.Name);

        return claim is null ? Unauthorized() : Ok(await _userService.GetUserRoutesAsync(claim.Value, HttpContext.RequestAborted));
    }

    [HttpGet("role")]
    [PermisstionDefinition("获取角色码")]
    public async Task<IActionResult> GetRoleCodesAsync()
    {
        var claim = HttpContext.User.Claims.FirstOrDefault(n => n.Type is "name" or ClaimTypes.Name);

        return claim is null ? Unauthorized() : Ok(await _userService.GetRoleCodesAsync(claim.Value, HttpContext.RequestAborted));
    }
}